package com.training.admin.web.controller.system;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.support.QueryOrder;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.training.admin.entity.principal.Principal;
import com.training.admin.entity.search.AccountSearch;
import com.training.admin.entity.security.Login;
import com.training.admin.service.PrincipalService;

/**
 * 
 * @author Rockett
 * 
 */
@Controller
@RequestMapping("/accounts")
@MenuSetting("menu-system-management")
public class AccountController {
 
	private static final Logger logger = LoggerFactory.getLogger(AccountController.class);
    
    @Autowired
    private PrincipalService principalService;
    

    /**
     * 
     * 用户列表
     * 
     * @return
     */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
    public ModelAndView list(Page page, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("account/account-list");
		int totals = principalService.count(new Login());
		if(totals > 0) {
			List<Principal> accounts = principalService.listByPage(Principal.class,new QueryOrder("id", "ASC"),page.with(totals));
			page.calculate();
			modelAndView.addObject("page", page);
	        modelAndView.addObject("accounts", accounts);
		}
        modelAndView.addObject("totals", totals);
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
		return modelAndView;
    }

	
    /**
     * onSearch
     * 
     * @param accountSearch
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-account-management")
    public ModelAndView onSearch(AccountSearch accountSearch, Page page, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("account/account-list");
        int totals = principalService.count(Principal.class, accountSearch.getFilter());
        if(totals > 0){
            List<Principal> accountList = principalService.search(Principal.class, accountSearch, page.with(totals));
            modelAndView.addObject("accounts", accountList);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        }
        return modelAndView;
        
    }

	/**
	 * 帐户详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
	public ModelAndView view() {
		ModelAndView modelAndView = new ModelAndView("account/account-view");
		return modelAndView;
	}

	/**
	 * 帐户查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
	public ModelAndView search() {
		ModelAndView modelAndView = new ModelAndView("account/account-search");
		return modelAndView;
	}

	/**
	 * 点击修改
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
	public ModelAndView edit(@PathVariable("id") Long id) {
		Principal account = principalService.load(Principal.class, id);
		ModelAndView modelAndView = new ModelAndView("account/account-edit");
		modelAndView.addObject("account", account);
		return modelAndView;
	}
	

	/**
	 * 点击删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
	public ModelAndView disable(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("account/account-delete");
		Principal principal = principalService.load(Principal.class, id);
		modelAndView.addObject("currentAccount", principal);
		return modelAndView;
	}
	
	/**
	 * 重置密码
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/reset", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
	public ModelAndView resetPassword(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("account/account-reset-password");
		modelAndView.addObject("id", id);
		return modelAndView;
	}
	/**
	 * 重置密码提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/reset", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-account-management")
	public @ResponseBody  HttpResult onResetPassword(@Preloading("accountId") Principal principal,
            @RequestParam("password") String password) {
        HttpResult httpResult = new HttpResult();
        principalService.resetPassword(principal, password);
        httpResult.success().message("重置密码成功！");
        return httpResult;
	}
	
	/**
	 * 修改提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-account-management")
	public @ResponseBody HttpResult onEdit(@Preloading("accountId") Principal principal) {
		HttpResult httpResult = new HttpResult();
		principalService.update(principal.update(new Date()));
		httpResult.success().message("修改帐户信息成功");
		return httpResult;
	}
	/**
	 * 修改提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.PATCH , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-account-management")
	public @ResponseBody HttpResult onDelete(@Preloading("accountId") Principal principal) {
		HttpResult httpResult = new HttpResult();
		//disable account 
		principal.setDisabled(true);
		principalService.update(principal.update(new Date()));
		httpResult.success().message("删除帐户成功");
		return httpResult;
	}

	/**
	 * 点击新增
	 * 
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	@MenuSetting("submenu-account-management")
	public ModelAndView create() {
		ModelAndView modelAndView = new ModelAndView("account/account-create");
		return modelAndView;
	}

	/**
	 * 新增提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-account-management")
	public  @ResponseBody HttpResult onCreate(Principal principal) {
        HttpResult httpResult = new HttpResult();
        try {
    		principalService.create(principal);
            httpResult.success().message("创建用户成功！");
		} catch (Exception e) {
			httpResult.fail("500").message("创建用户失败! " + e.getMessage());
			logger.error("#onCreate() - create user fail, exception is [{}]", e);
		}
        return httpResult;

	}
	
}
